package control.connector;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class ImageMap extends JPanel{
	private BufferedImage image;
	private File imageFile;
	private String name;
	private double minLat, maxLat, minLong, maxLong;
	
	public ImageMap(File source){
		this.imageFile = source;

		this.name = this.imageFile.getName();
		//Creating the image from file
		restoreImage();
		
		String[] splitName = name.split("\\.");
				
		//Reading max and min coordinates for image
		Scanner sc = null;
		try {
			sc = new Scanner(new File("src/"+splitName[0]+".txt"));
			minLat = Float.parseFloat(sc.nextLine());
			maxLat = Float.parseFloat(sc.nextLine());
			minLong = Float.parseFloat(sc.nextLine());
			maxLong = Float.parseFloat(sc.nextLine());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("No coordinates found.");
		}
		
		
	}
	
	//Painting the component
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		g.drawImage(image,0,0,this);
	}
	
	//Get the image
	public BufferedImage getImage(){
		return this.image;
	}
	
	//Restore the image from the file
	public void restoreImage(){
		try {	this.image = ImageIO.read(imageFile);	
		} catch (IOException e) {e.printStackTrace();}
	}
	
	//Change the base map file
	public void changeFile(File file){
		this.imageFile = file;
		restoreImage();
	}
	
	//Return the name of the map file
	public String getName(){
		return this.name;
	}
	
	//The converter for gps coordinates
	public int[] gpsConvert(double x, double y){
		int[] pix = new int[2];
		
		//pix[0]= Lat;
		//pix[1]= Long;
		
		pix[0] =(int) ((x-minLat)*(1084/(maxLat-minLat))+0.5);
		pix[1] =(int) ((y-minLong)*707/(maxLong - minLong)+0.5);
		//(1084x707 is the base resolution of the map)
		
		return pix;
	}

}
